<template>
	<view class="body-view">
		<!--导航和状态栏-->
		<view class="state-navigation">
			<view class="slim_header_navigation d-flex a-center j-center" >
				<view class="left_box" @tap="goBack">
					<view class="left_box-text">上一步</view>
				</view>
				<view class="title">上传封面</view>
				<view class="right_box">
					<!-- <image src="/static/center/dian.png" class="dian"></image> -->
				</view>
			</view>
		</view>
		<!-- 顶部位置占位 -->
		<view style="height:calc(120rpx + var(--status-bar-height));"></view>
		<view class="top-frame">
			<view class="top-frame-item">
				<view class="frame-item-title d-flex a-center">
					<view class="item-title-left"></view>
					<view class="item-title-text">请为你的方案上传一张封面图</view>
				</view>
				<view  @tap="select" class="frame-item-upload d-flex a-center j-center">
					<view v-if="formData.photo==''" class="d-flex d-c a-center j-center">
						<i class="icon icon-tupianlv" style="font-size: 50rpx;color: #CCCCCC;"></i>
						<view class="item-upload-text">点此上传</view>
					</view>
					<image v-else style="width: 100%;height: 100%;" mode="aspectFill" :src="formData.photo"></image>
				</view>
			</view>
		</view>
		<view style="height: 20rpx;"></view>
		<view class="top-frame">
			<view class="top-frame-item">
				<view class="frame-item-title d-flex a-center">
					<view class="item-title-left"></view>
					<view class="item-title-text">允许转存</view>
				</view>
				<view class="content-row d-flex a-center j-between">
					<view class="row-text">所有人</view>
					<tm-switch
				        linear="left"
				        linearDeep="accent"
						v-model="isAll"
				        :defaultValue="isAll"
				        @change="changeAll"
				        color="rgba(15, 95, 70, 0.30)"
				        :barColor="
				            isAll
				                ? 'rgba(35, 226, 166, 1)'
				                : 'rgba(195, 204, 202, 1)'
				        "
				        barIcon=""
				        size="normal"
				    ></tm-switch>
				</view>
				<view class="content-row d-flex a-center j-between">
					<view class="row-text">仅群友</view>
					<tm-switch
				        linear="left"
				        linearDeep="accent"
				        v-model="isFriend"
				        :defaultValue="isFriend"
						@change="changeFriend"
				        color="rgba(15, 95, 70, 0.30)"
				        :barColor="
				            isFriend
				                ? 'rgba(35, 226, 166, 1)'
				                : 'rgba(195, 204, 202, 1)'
				        "
				        barIcon=""
				        size="normal"
				    ></tm-switch>
				</view>
				<view class="content-row-release d-flex a-center j-between">
					<view>
						<view class="d-flex d-c j-center">
							<view class="-row-release-title d-flex a-center">
								<view class="release-title-left"></view>
								<view class="release-title-text">发布到</view>
								<view class="release-title-plan">【计划-方案广场】</view>
							</view>
							<view class="-row-release-explain">(可被平台所有胖友看到)</view>
						</view>
					</view>
					<view>
						<tm-switch
							:disabled="disabledSquare"
						    linear="left"
						    linearDeep="accent"
						    v-model="isSquare"
						    :defaultValue="isSquare"
						    color="rgba(15, 95, 70, 0.30)"
							@click="clickSquare"
						    :barColor="
						        isSquare
						            ? 'rgba(35, 226, 166, 1)'
						            : 'rgba(195, 204, 202, 1)'
						    "
						    barIcon=""
						    size="normal"
						></tm-switch>
					</view>
				</view>
			</view>
		</view>
		<view class="bottom-btn d-flex a-center j-center">
			<tm-button
				_style="margin: 0;font-weight: 600;"
				:width="690"
				:height="80"
				:shadow="-1"
				round="5"
				:linear-color="['#64F1C5', '#29DBA3']"
				linear="left"
				:fontSize="32"
				fontColor="#ffffff"
				:label="`${formData?.isAdd?'完成创建':'保存'}`"
				@tap="submit"
			></tm-button>
		</view>
		
		<cropper
		    mode="free"
		    :width="200"
		    :height="200"
		    :maxWidth="1024"
		    :maxHeight="1024"
		    :url="imgurl"
		    @cancel="cancel"
		    @ok="complete"
		></cropper>
	</view>
</template>

<script setup lang="tsx" name="programmeCover">
import { ref } from "vue";
import { onLoad } from '@dcloudio/uni-app';
import { closeLoading,uploadFile } from '@/utils/utils';
import { addUserPlan,updateUserPlan } from "@/api/api";
import { userData as userDataStore } from "@/store/userData";
import cropper from "@/components/cropper";
import { chooseImage } from "@/utils/utils";

const userData: any = userDataStore();
const formData:any = ref();
const disabledSquare = ref(true);
onLoad((options:any) => {
	formData.value = JSON.parse(options.formData);
	countSwitchState();
	disabledSquare.value = !availableSquare();
	//console.log(disabledSquare.value,formData.value.isPublic)
	if(!disabledSquare.value){
		if(formData.value.isPublic==1){
			isSquare.value = true
		}else{
			isSquare.value = false
		}
	}else{
		isSquare.value = false
	}
	
});
const goBack = () => {
	countSwitchValue();
	uni.$emit('setFormData', formData.value);
	uni.navigateBack();
};
const isAll = ref(true);//是否所有人可转存
const isFriend = ref(false);//是否只有朋友群可转存
const isSquare = ref(false);//是否发布到广场
const changeAll = (e:any) => {
	if(e)isFriend.value = false;
	return e;
}
const changeFriend = (e:any) => {
	if(e)isAll.value = false;
	return e;
}
const clickSquare = () => {
	if(disabledSquare.value){
		uni.showToast({
		    icon: "none",
		    title: '您的方案过于简略，无法发布到方案广场',
		    duration: 1500,
		});
	}
}
const availableSquare = () => {
		let foodType = 0;
		if(formData.value.breakfast.length == 0)foodType++;
		if(formData.value.lunch.length == 0)foodType++;
		if(formData.value.dinner.length == 0)foodType++;
		if(formData.value.addFood.length == 0)foodType++;
		let foodNumber= 0;
		foodNumber += formData.value.breakfast.length;
		foodNumber += formData.value.lunch.length;
		foodNumber += formData.value.dinner.length;
		foodNumber += formData.value.addFood.length;
		if(foodType>=3||foodNumber<10){
			/*
			uni.showToast({
			    icon: "none",
			    title: '您的方案过于简略，无法发布到方案广场',
			    duration: 1500,
			});
			*/
			return false;
		}
	return true;
}

//根据开关状态设置值
const countSwitchValue = () => {
	if(!isAll.value&&!isFriend.value)formData.value.relayStatus = 0;
	if(isAll.value)formData.value.relayStatus = 1;
	if(isFriend.value)formData.value.relayStatus = 2;
	if(isSquare.value){
		formData.value.isPublic = 1;
	}else{
		formData.value.isPublic = 0;
	}
	//console.log(formData.value)
}
//根据值设置开关状态
const countSwitchState = () => {
	if(formData.value.relayStatus==0){
		isAll.value = false;
		isFriend.value = false;
	}
	if(formData.value.relayStatus==1){
		isAll.value = true;
		isFriend.value = false;
	}
	if(formData.value.relayStatus==2){
		isAll.value = false;
		isFriend.value = true;
	}
	if(formData.value.isPublic==1){
		isSquare.value = true;
	}
	if(formData.value.isPublic==0){
		isSquare.value = false;
	}
	
}
const submit = () => {
	if(formData.value.photo==""){
		uni.showToast({
		    icon: "none",
		    title: '请上传一张封面图',
		    duration: 1500,
		});
		return;
	}
	let userPlanDetailList:any = [];
	formData.value.breakfast.forEach((item:any) => {
		userPlanDetailList.push({
			type:1,
			targetHeat:item.eatHeatQuantity,
			targetQuantity:item.eatGrams,
			targetId:item.foodId,
			targetHeatLevel:item.healthLight,
			targetName:item.foodName,
			unit:item.unit,
			
		});
	});
	formData.value.lunch.forEach((item:any) => {
		userPlanDetailList.push({
			type:2,
			targetHeat:item.eatHeatQuantity,
			targetQuantity:item.eatGrams,
			targetId:item.foodId,
			targetHeatLevel:item.healthLight,
			targetName:item.foodName,
			unit:item.unit
		});
	});
	formData.value.dinner.forEach((item:any) => {
		userPlanDetailList.push({
			type:3,
			targetHeat:item.eatHeatQuantity,
			targetQuantity:item.eatGrams,
			targetId:item.foodId,
			targetHeatLevel:item.healthLight,
			targetName:item.foodName,
			unit:item.unit
		});
	});
	formData.value.addFood.forEach((item:any) => {
		userPlanDetailList.push({
			type:4,
			targetHeat:item.eatHeatQuantity,
			targetQuantity:item.eatGrams,
			targetId:item.foodId,
			targetHeatLevel:item.healthLight,
			targetName:item.foodName,
			unit:item.unit
		});
	});
	formData.value.sports.forEach((item:any) => {
		userPlanDetailList.push({
			type:6,
			targetHeatLevel:item.heatLevel,
			targetHeat:item.heat,
			targetQuantity:item.time,
			targetId:item.code,
			targetName:item.name,
			unit:item.unit
		});
	});
	let heatIsPoor = formData.value.heatIsPoor.split("-");
	formData.value.heatIsPoorStart = heatIsPoor[0];
	formData.value.heatIsPoorEnd = heatIsPoor[1];
	if(heatIsPoor[1]==null)formData.value.heatIsPoorEnd = heatIsPoor[0];
	formData.value.userId = userData.id;
	formData.value.userPlanDetailList = userPlanDetailList;
	if(isSquare.value){
		formData.value.isPublic = 1;
	}else{
		formData.value.isPublic = 0;
	}
	let message = "创建成功";
	if(formData.value.isPublic == 1)message = "创建成功并已发送到方案广场";
	
	//找到应该返回的层级
	let pages = getCurrentPages();
	let toIndex = pages.findIndex((item:any) => item.route == "pages/programme/programme");
	let delta = pages.length - toIndex -1;
	if(formData.value.isAdd){
		addUserPlan(formData.value).then((res:any) => {
			if(res.success){
				//uni.removeStorageSync('programmeCreate');
				//uni.removeStorageSync('programmeCreate');
				uni.navigateBack({
					delta:delta,
					success:() => {
						uni.removeStorageSync('programmeCreate');
						uni.showToast({
						    icon: "none",
						    title: message,
						    duration: 1500,
						});
					}
				});
			}
		});
	}else{
		updateUserPlan(formData.value).then((res:any) => {
			if(res.success){
				//uni.removeStorageSync('programmeCreate');
				uni.navigateBack({
					delta:delta,
					success:() => {
						uni.showToast({
						    icon: "none",
						    title: '已保存',
						    duration: 1500,
						});
					}
				});
			}
		});
	}
	
}
//图片上传
const imgurl = ref("");
const select = () => {
    chooseImage({
        count: 1,
        success: (rst) => {
            // 设置url的值，显示控件
            imgurl.value = rst.tempFilePaths[0];
			console.log(imgurl.value)
        },
    });
};
const cancel = () => {
    imgurl.value = "";
};
const complete = async (ev:any) => {
    const result:any = await uploadFile(ev.path).catch(()=>{
        uni.showToast({
            icon: "none",
            title: "上传图片失败",
        });
    })
	//console.log(result)
    if(result){
        const index = result.lastIndexOf('.');
        const name = result.substring(0,index);
        const ext = result.substring(index,result.length);
        formData.value.photo = `${name}-big${ext}`;
        uni.$emit('userheadChange',result)
        setTimeout(()=>{
            closeLoading();
            imgurl.value = "";
        },500)
    }

};
</script>

<style lang="scss" scoped>
@import './programmeCover.scss';
</style>
